package cn.kent.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.transaction.RabbitTransactionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {
    public static final String MSG_QUEUE_NAME = "msg_queue_name";
    public static final String MSG_EXCHANGE_NAME = "msg_exchange_name";

    @Bean
    Queue msgQueue() {
        return new Queue(MSG_QUEUE_NAME, true, false, false);
    }

    @Bean
    DirectExchange msgExchange() {
        return new DirectExchange(MSG_EXCHANGE_NAME, true, false);
    }

    @Bean
    Binding msgBinding() {
        return BindingBuilder.bind(msgQueue())
                .to(msgExchange())
                .with(MSG_QUEUE_NAME);
    }

    /**
     * 事务管理器
     * @param connectionFactory
     * @return
     */
    @Bean
    RabbitTransactionManager rabbitTransactionManager(ConnectionFactory connectionFactory) {
        return new RabbitTransactionManager(connectionFactory);
    }

    @Bean
    RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        // 开启事务模式
        rabbitTemplate.setChannelTransacted(true);
        return rabbitTemplate;
    }

}
